import { tokenLocalData } from '@/utils/storage/local-data'
import '@/config/index'
import { ResultCode } from '@/config/request'
import { redirectLoginPage } from '@/utils/index'
import { TokenExpired } from '@/global/index'

const token = tokenLocalData.get()

export default function http() {
  uni.$u.http.setConfig({
    baseUrl: '/api',
    header: {
      'Content-Type': 'application/json'
    }
  })

  //请求拦截器
  uni.$u.http.interceptor.request = (config: any) => {
    if (!config.header.custom.ignoreToken && !token) {
      // 跳转至登录页
      return Promise.reject(config)
    } else {
      config.header.token = token
    }
    return config
  }

  //响应拦截器
  uni.$u.http.interceptor.response = (res: any) => {
    /* 对响应成功做点什么 （statusCode === 200），必须return response*/
    const { code, data, message } = res
    if (code === ResultCode.UNAUTHORIZED) {
      redirectLoginPage(TokenExpired)
      /* uni.reLaunch({
        url: '/pages/login/index',
        success: () => {
          uni.showToast({
            title: '登录失效，请重新登录',
            icon: 'none'
          })
        },
        fail: e => {
          console.log(e)
        }
      }) */
    } else if (code === ResultCode.SUCCESS) {
      return data
    } else {
      uni.showToast({
        title: message,
        duration: 2000,
        icon: 'none',
        mask: true
      })
      return Promise.reject(data)
    }
  }
}
